package com.shop.service.impl;

import com.shop.domain.Cart;
import com.shop.service.CartService;
import com.shop.util.TokenDecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TokenDecode tokenDecode;
    @Override
    public void add(Cart cart) {
        //获取当前用户名
        String userName = tokenDecode.getUserInfo().get("user_name");
        //通过指定key查询value 查询购物车
        Cart c = (Cart) redisTemplate.boundHashOps("Cart" + userName).get(cart.getProductId());
        //如果有 在原数据上添加
        if(c !=null){
            c.setNum(c.getNum()+cart.getNum());
            c.setMoney(c.getUnitPrice().multiply(BigDecimal.valueOf(c.getNum())));
            redisTemplate.boundHashOps("Cart" + userName).put(cart.getProductId(), c);
        }else{
            // 如果没有 新增
            redisTemplate.boundHashOps("Cart" + userName).put(cart.getProductId(), cart);
        }
    }

    @Override
    public List<Cart> findList() {
        String userName = tokenDecode.getUserInfo().get("user_name");
        return (List<Cart>) redisTemplate.boundHashOps("Cart" + userName).values();
    }

    @Override
    public void update(Cart cart) {
        String userName = tokenDecode.getUserInfo().get("user_name");
        // 覆盖 修改
        redisTemplate.boundHashOps("Cart" + userName).put(cart.getProductId(), cart);
    }

    @Override
    public void delete(String ids) {
        String[] split = ids.split(",");
        //获取用户名
        String username = tokenDecode.getUserInfo().get("user_name");
        for (String id : split) {
            redisTemplate.boundHashOps("Cart"+username).delete(Long.valueOf(id));
        }
    }
}
